<template>
	<div>7777777</div>
</template>

<script>
    import getSearch from '../../utils/getUrlSearch';
    import { RECEIVE_STORE, RECEIVE_DISTANCE } from '../../config/postMessage-types.js'
    import axios from 'axios'
    var pos;
    var inArea;
    var isError;
    //门店列表
    var storeList = [];
    //是否获取到门店列表的状态，默认false
    var storeListStatus = 0;
    //当前定位位置
    var currentPos;
    //倒计时变量
    var countDown;
	export default {
		data() {
            return {
                
            }
        },
        methods:{
            //获取门店列表
            async getStoreList() {
                let options = {
                    url: api.base_host + '/baseStore/getRestStore',
                    method: 'get'
                }
                let res = await axios(options);
                res.data.returnCode && (storeList = res.data.data[0]);
                res.data.returnCode && (storeListStatus = 1);
            },
            //定位成功发送给rn
            locateSuccess() {
                let RnParams = {
                    type: RECEIVE_DISTANCE,
                    params: {
                        storeList: storeList,
                        inArea: inArea,
                        currentPos: currentPos
                    }
                }
                console.log(RnParams,'RnParams')
                window.postMessage(JSON.stringify(RnParams));
            },
            //定位失败发送给rn
            locateFailed() {
                let a1 = {
                    type: RECEIVE_DISTANCE,
                    params: {
                        message: 'locateFailed'
                    }
                }
                window.postMessage(JSON.stringify(a1));
            },
            //根据经纬度计算距离，单位是千米
            calculate(lat1, lng1, lat2, lng2) {
                var radLat1 = lat1 * Math.PI / 180.0;
                var radLat2 = lat2 * Math.PI / 180.0;
                var a = radLat1 - radLat2;
                var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
                var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
                s = s * 6378.137;
                s = Math.round(s * 10000) / 10000;
                return s
            },
            //计算到门店的距离并添加到门店列表中
            calculateDistance(res) {
                storeListStatus ? this.sendToRn(res) : setTimeout(() => {this.calculateDistance.bind(this, res)}, 300);
            },
            //计算距离并发送给Rn
            sendToRn(res) {
                storeList.map(ele => {
                    //计算到门店距离
                    (ele.positionLng && ele.positionLat) 
                        ? ele.distance = this.calculate(ele.positionLat, ele.positionLng, res.position.lat, res.position.lng).toFixed(2) 
                        : ele.distance = 0;
                })
                for(let i = 0;i < storeList.length;i++) {
                    for(let j = i + 1;j < storeList.length;j++){
                        if(storeList[i].distance < storeList[j].distance) {
                            let temp = storeList[i];
                            storeList[i] = storeList[j];
                            storeList[j] = temp;
                        }
                    }
                }
                storeList = storeList.reverse();
                let zeroArr = [];
                let countArr = [];
                storeList.map(ele => {
                    ele.distance == 0 ? zeroArr.push(ele) : countArr.push(ele);
                })
                storeList = countArr.concat(zeroArr);
                //发送带有距离的门店地址给RN
                pos = storeList;
                //计算是否在门店配送范围内
                this.calculateInArea(res);
            },
            //计算是否在门店配送范围内
            async calculateInArea(res) {
                let list = JSON.parse(getSearch().storeIdList);
                let storeList = [];
                Array.isArray(list) && list.map(ele => {
                    storeList.push(JSON.stringify(ele))
                })
                this.storeIdList = storeList;
                let options = {
                    // url: api.customer_host + '/address/getTMS',
                    url: api.tmsUrl + 'centralManagerApi/centralManagerObject',
                    method: 'post',
                    data: {
                        judgeInBaselatticeByStoreId: {
                            longitudeandlatitude: res.position.lng + ',' + res.position.lat,
                            storeIdList: storeIdList
                        }
                    }
                }
                let result = await axios(options);
                if(result.data.returnCode) {
                    inArea = result.data.data[0];
                    this.locateSuccess()
                }else {
                    inArea = 'unmatch'
                }
            },
            //定位
            getLocation() {
                //开启高德地图
                try{
                    var map = new AMap.Map('allmap', {});
                }catch(err) {
                    setTimeout(() => {
						this.getLocation();
					},300)
					return
                }
                map.plugin(['AMap.Geolocation'], () => {
                    var geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true,               //是否使用高精度定位，默认:true
                        timeout: 10000,                          //超过5秒后停止定位，默认：无穷大
                        maximumAge: 0,                          //定位结果缓存0毫秒，默认：0
                    });
                    //计时5s，防止超时未调用err函数
                    countDown = setTimeout(() => {
                        isError = true;
                    }, 5000);
                    //开始定位
                    geolocation.getCurrentPosition();
                    //定位成功
                    geolocation.on('complete', res => {
                        console.log(JSON.stringify(res))
                        clearTimeout(countDown);
                        countDown = null;
                        //当前定位位置
                        currentPos = res;
                        //计算到门店的距离
                        this.calculateDistance(res);
                    });
                    //定位失败
                    geolocation.on('error', (err) => {
                        console.log(err.message,'234234')
                        this.locateFailed()
                    });
                })
            },
            initScript() {
                //判断如果有script就删掉
                if (document.querySelector("#amap-box")){
                    document.body.removeChild(document.querySelector("#amap-box"));
                }
                let amapBox = document.createElement("div");
                amapBox.setAttribute("id", "amap-box");
                let script1 = document.createElement("script");
                script1.onload = () => {
                    let script2 = document.createElement("script");
                    script2.onload = () => {
                        setTimeout(() => {
                            this.getLocation();
                        },300)
                    }
                    script2.src = "https://webapi.amap.com/ui/1.0/main.js";
                    amapBox.insertAdjacentElement("beforeend", script2);
                };
                if(this.getIosVersion()){
                    script1.src = 'https://webapi.amap.com/maps?v=1.3&key=9bfe3d8b8882b7d3e4c23e43d38b18ba';
                }else {
                    script1.src = 'https://webapi.amap.com/maps?v=1.4.6&key=9bfe3d8b8882b7d3e4c23e43d38b18ba';
                }
                amapBox.insertAdjacentElement("beforeend", script1);
                document.body.appendChild(amapBox);
            },
            //判断ios版本
            getIosVersion() {
                var u = navigator.userAgent, app = navigator.appVersion;
                var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
                var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
                if (isAndroid) {
                    return false//这个是安卓操作系统
                }
                if (isIOS) {//这个是ios操作系统
                    var ver = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
                    // ver = parseInt(ver[1], 10);
                    var IosVersion = (ver[1] || '0') + (ver[2] || '0') + (ver[3] || '0');
                    if(Number(IosVersion) < 935) {
                        return true
                    }else {
                        return false
                    }
                }
            }
        },
        async mounted() {
            this.getStoreList();
            this.initScript();
            // let options = {
            //     url: api.tmsUrl + 'centralManagerApi/centralManagerObject',
            //     method: 'post',
            //     data: {
            //         judgeInBaselatticeByStoreId: {
            //             longitudeandlatitude: '108.389724,22.816511',
            //             storeIdList: storeList
            //         }
            //     }
            // }
            // let result = await axios(options);
        }
	}
</script>
<style>
</style>